
import { debug } from '../../config/index'

import store from 'store'


/**
 * 处理需要存储的state
 * @param type
 * @param payload
 */
const handleStore = function (type, payload) {

  if(typeof payload != 'object') return;

  const __store = payload.__store;
  if(typeof __store == 'undefined') return;

  if(__store === false){
    store.remove(type);
  }

  let storeKeys = store.get('vuex_keys')||[];
  if( storeKeys.indexOf(type) == -1) storeKeys.push(type);
  store.set('vuex_keys', storeKeys);
  delete payload.__store;
  if( typeof __store == 'object' && __store.expire){
    store.set(type, payload, new Date().getTime() + __store.expire);
  }else{
    store.set(type, payload);
  }
}

/**
 * 获取vuex存储的key，组合需要还原的数据
 * @returns {{}}
 */
const storeDatas = function () {
  let storeKeys = store.get('vuex_keys')||[],
    vuexStoreMap = {};
  storeKeys.forEach(function (key) {
    let value = store.get(key);
    if(value) vuexStoreMap[key] = value;
  });
  return vuexStoreMap;
};


/**
 * 初始化数据
 * @param store
 */
export const initStoreData =  store => {

    // 还原存储客户端的数据
    let _store_datas = storeDatas();
    for( let key in _store_datas){
        debug && console.info('init data', key);
        store.commit(key, _store_datas[key]);
    }

    store.subscribe((mutation, state) => {
        const { type, payload } = mutation;
        handleStore(type, payload);

        // 登录情况下获取基本信息
        /*if( state.account.isLogin ){
            store.dispatch('getClientsAndMedias');
        }*/
    })

}
